package com.ledtechdesign.afcs;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;

import com.ledtechdesign.auth.AuthenticationFactory;
import com.ledtechdesign.service.Utils;

/**
 * Authenticator - generate Acorn authentication tokens
 */
public class Authenticator {
	private String authURL;
	Log logger = LogFactory.getLog(this.getClass());

	protected Authenticator(String url) {
		this.authURL = url;
	}

	/*
	 * get a guest authentication token
	 */
	public String guestLogin(String user) {
		return "g:"+user;
	}

	/*
	 * get a Renga authentication token give login and password
	 */
	public String login(String user, String pw,
			Map<String, String> retHeaders) throws Exception {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Content-Type", "text/xml");

		String data = "<request><username>" + user + "</username>"
				+ "<password>" + pw + "</password></request>";

		InputStream resp = Utils.http_post(this.authURL, data, headers);

		// if (Utils.DEBUG) logger.debug(resp);

		this.logger.debug("Response for Login(raw): " + resp);
		Element result = Utils.parseXML(resp);
		
		System.out.println(">>>>> "+Utils.printXML(result));
		this.logger.debug("Response for Login: " + result);

		if ("ok".equals(result.getAttribute("status"))) {
			Element authtoken = (Element) result.getElementsByTagName(
					"authtoken").item(0);
			if ("COOKIE".equals(authtoken.getAttribute("type"))) {
				retHeaders.put("Cookie", authtoken.getTextContent().trim());
				return null;
			} else {
				String a =authtoken
				.getTextContent().trim();
				return a;
			}
		} else {
			this.logger.debug(Utils.printXML(result));
			throw new Exception(Utils.printXML(result));
		}
	}
}
